package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/signintech/gopdf"
)

type Patient struct {
	ID            string   `json:"id"`
	Name          string   `json:"name"`
	Gender        string   `json:"gender"`
	Age           int      `json:"age"`
	Contact       string   `json:"contact"`
	MedicalRecord []Record `json:"medicalRecord"`
}

type Record struct {
	VisitDate time.Time `json:"visitDate"`
	Symptoms  string    `json:"symptoms"`
	Diagnosis string    `json:"diagnosis"`
	Treatment string    `json:"treatment"`
}

func generatePDF(patient Patient) error {
	pdf := gopdf.GoPdf{}
	pdf.Start(gopdf.Config{PageSize: *gopdf.PageSizeA4})
	pdf.AddPage()

	// 设置字体
	err := pdf.AddTTFFont("simhei", "./simhei.ttf") // 需要一个支持中文的字体文件
	if err != nil {
		return fmt.Errorf("failed to add font: %v", err)
	}
	pdf.SetFont("simhei", "", 12)

	// 添加患者基本信息
	pdf.Cell(nil, fmt.Sprintf("患者姓名: %s", patient.Name))
	pdf.Br(20)
	pdf.Cell(nil, fmt.Sprintf("性别: %s", patient.Gender))
	pdf.Br(20)
	pdf.Cell(nil, fmt.Sprintf("年龄: %d", patient.Age))
	pdf.Br(20)
	pdf.Cell(nil, fmt.Sprintf("联系方式: %s", patient.Contact))
	pdf.Br(20)

	// 添加病历记录
	for _, record := range patient.MedicalRecord {
		pdf.Cell(nil, fmt.Sprintf("就诊日期: %s", record.VisitDate.Format("2006-01-02")))
		pdf.Br(20)
		pdf.Cell(nil, fmt.Sprintf("症状: %s", record.Symptoms))
		pdf.Br(20)
		pdf.Cell(nil, fmt.Sprintf("诊断: %s", record.Diagnosis))
		pdf.Br(20)
		pdf.Cell(nil, fmt.Sprintf("治疗方案: %s", record.Treatment))
		pdf.Br(20)
	}

	// 保存 PDF 文件
	err = pdf.WritePdf("patient_record.pdf")
	if err != nil {
		return fmt.Errorf("failed to write PDF: %v", err)
	}
	return nil
}

func pdfHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}

	// 解析请求体
	var patient Patient
	err := json.NewDecoder(r.Body).Decode(&patient)
	if err != nil {
		http.Error(w, "Failed to parse JSON data", http.StatusBadRequest)
		return
	}

	err = generatePDF(patient)
	if err != nil {
		http.Error(w, fmt.Sprintf("Failed to generate PDF: %v", err), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/pdf")
	http.ServeFile(w, r, "patient_record.pdf")
}

func main() {
	http.HandleFunc("/generate-pdf", pdfHandler)
	log.Println("Starting server on :8080...")
	log.Fatal(http.ListenAndServe(":8080", nil))
}
